package com.hexinfo.dmpro.dev.data.transfer.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hexinfo.dmpro.dev.data.transfer.model.DevDataExportList;
import lombok.extern.slf4j.XSlf4j;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Package
 * @ClassName ExcelUtils
 * @Description
 * @Author 29027
 * @Date 2024/1/4 15:41
 **/
public class ExcelUtils {
    public Log log = LogFactory.getLog(this.getClass());

    /**
     * @Method
     * @Description 创建导出文件
     * @Author gxd
     * @param[1] exportPath 导出目录
     * @param[2] downloadFileName 导出文件名
     * @return File
     * @Date 2024/1/4 15:42
     **/
    public static File createDatafile(String exportPath, String downloadFileName) throws IOException {
        //获取文件存储在服务器的目录
        // 创建目录
        File myFileExportPath = new File(exportPath);
        if (!myFileExportPath.exists()) {
            myFileExportPath.mkdirs();
        }
        byte[] fileNameBytes = downloadFileName.getBytes("UTF-8");
        // 创建文件
        File myFile = new File(new String(fileNameBytes, "UTF-8"));
        // 判断文件是否存在，如不存在则调用createNewFile()创建新目录，否则跳至异常处理代码
        if (!myFile.exists()) {
            myFile.createNewFile();
        }
        return myFile;
    }

    /**
     * @Method
     * @Description 写入数据
     * @Author gxd
     * @param[1] saveFile
     * @param[2] workbook
     * @Date 2024/1/4 15:48
     **/
    public static void writeDownloadFileData(File saveFile, Workbook workbook) throws IOException {
        final FileOutputStream outputStream = new FileOutputStream(saveFile);
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    }
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>(16);
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            /*
             * Returns the value of the field represented by this {@code Field}, on the
             * specified object. The value is automatically wrapped in an object if it
             * has a primitive type.
             * 注:返回对象该该属性的属性值，如果该属性的基本类型，那么自动转换为包装类
             */
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }
}
